
package com.irs.irsforum.security;

import com.irs.irsforum.entity.Resources;
import com.irs.irsforum.entity.User;
import com.irs.irsforum.service.IStudentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @author yihuili
 * @since 2020-01-18
 */
public class AuthStudentInterceptor implements HandlerInterceptor {

    private static final Logger logger =
            LoggerFactory.getLogger(AuthStudentInterceptor.class);

    @Autowired
    IStudentService iStudentService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("开始认证：" + new Date().toString());
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            response.setStatus(HttpStatus.NO_CONTENT.value());
            return true;
        }
        Long userId;
        try {
            userId = (long) request.getSession().getAttribute("userId");
        } catch (Exception e) {
            response.sendRedirect(Resources.getIRSINDEXPAGE());
            logger.error("信息认证失败");
            return false;
        }
        logger.info("userId={}", userId);
        User user = new User();
        user.setId(userId);
        if (userId == null || userId == 0) {
            logger.error("信息认证失败,stuId ={}", userId);
            response.sendRedirect(Resources.getIRSINDEXPAGE());
        } else if (userId == -1) {
            user.setAuthenticated(false);
        } else {
            user.setAuthenticated(true);
            logger.info("信息认证成功");
        }
        SecurityContext securityCxt = SecurityContextHolder.getContext();
        securityCxt.setAuthentication(user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }


}